const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { authenticateToken, getNextId, logUserOperation } = require('../untils/untils');
const dayjs = require('dayjs');

// 获取用户控制日志列表
router.get('/', authenticateToken, async (req, res) => {
    try {
        const {
            username,
            action_type,
            operation_module,
            status,
            start_date,
            end_date,
            page = 1,
            page_size = 20
        } = req.query;

        let sql = ` SELECT ucl.*, u.emp_id, e.emp_name FROM user_ctrl_log ucl LEFT JOIN user u ON ucl.username = u.username LEFT JOIN employee e ON u.emp_id = e.emp_id WHERE 1 = 1 `;
        let params = [];

        // 添加查询条件
        if (username) {
            sql += ` AND ucl.username LIKE ?`;
            params.push(`%${username}%`);
        }
        if (action_type) {
            sql += ` AND ucl.operation_type = ?`;
            params.push(action_type);
        }
        if (operation_module) {
            sql += ` AND ucl.operation_module LIKE ?`;
            params.push(`%${operation_module}%`);
        }
        if (status) {
            sql += ` AND ucl.status = ?`;
            params.push(status);
        }
        if (start_date) {
            sql += ` AND DATE(ucl.operation_time) >= ?`;
            params.push(start_date);
        }
        if (end_date) {
            sql += ` AND DATE(ucl.operation_time) <= ?`;
            params.push(end_date);
        }

        // 添加排序
        sql += ` ORDER BY ucl.operation_time DESC`;

        // // 添加分页
        const pageNum = parseInt(page) || '1';
        const pageSize = parseInt(page_size) || '20';
        const offset = (pageNum - 1) * pageSize;
        params.push(pageSize, offset);

        const [result] = await db.query(sql, params);

        result.forEach(item => {
            item.operation_time = dayjs(item.operation_time).format('YYYY-MM-DD HH:mm:ss');
        });

        // 获取总数
        let countSql = `
            SELECT COUNT(*) as total
            FROM user_ctrl_log ucl
            WHERE 1 = 1
        `;
        let countParams = [];

        if (username) {
            countSql += ` AND ucl.username LIKE ?`;
            countParams.push(`%${username}%`);
        }
        if (action_type) {
            countSql += ` AND ucl.operation_type = ?`;
            countParams.push(action_type);
        }
        if (operation_module) {
            countSql += ` AND ucl.operation_module LIKE ?`;
            countParams.push(`%${operation_module}%`);
        }
        if (status) {
            countSql += ` AND ucl.status = ?`;
            countParams.push(status);
        }
        if (start_date) {
            countSql += ` AND DATE(ucl.operation_time) >= ?`;
            countParams.push(start_date);
        }
        if (end_date) {
            countSql += ` AND DATE(ucl.operation_time) <= ?`;
            countParams.push(end_date);
        }

        const [countResult] = await db.execute(countSql, countParams);
        const total = countResult[0].total;

        await logUserOperation(req, '查询', '获取用户控制日志', '获取用户控制日志成功', '成功');
        res.json({
            success: true,
            message: '获取用户控制日志成功',
            data: {
                list: result,
                pagination: {
                    page: pageNum,
                    page_size: pageSize,
                    total: total,
                    total_pages: Math.ceil(total / pageSize)
                }
            }
        });
    } catch (error) {
        console.error('获取用户控制日志失败:', error);
        await logUserOperation(req, '查询', '获取用户控制日志', '获取用户控制日志失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取用户控制日志失败',
            error: error.message
        });
    }
});

// 添加用户控制日志
router.put('/add', authenticateToken, async (req, res) => {
    try {
        const {
            username,
            operation_type,
            operation_module,
            operation_desc,
            ip_address,
            user_agent,
            status,
            error_message
        } = req.body;

        const log_id = await getNextId('LOG', 'log_id', 'user_ctrl_log', 5);
        const operation_time = dayjs().format('YYYY-MM-DD HH:mm:ss');

        let sql = `
            INSERT INTO user_ctrl_log 
            (log_id, username, operation_type, operation_module, operation_desc, ip_address, user_agent, operation_time, status, error_message) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `;
        let params = [
            log_id,
            username,
            operation_type,
            operation_module,
            operation_desc,
            ip_address,
            user_agent,
            operation_time,
            status,
            error_message
        ];

        const [result] = await db.execute(sql, params);

        await logUserOperation(req, '添加', '添加用户控制日志', '添加用户控制日志成功', '成功');
        res.json({
            success: true,
            message: '添加用户控制日志成功',
            data: result
        });
    } catch (error) {
        console.error('添加用户控制日志失败:', error);
        await logUserOperation(req, '添加', '添加用户控制日志', '添加用户控制日志失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '添加用户控制日志失败',
            error: error.message
        });
    }
});

// 获取操作类型统计
router.get('/operation-types', authenticateToken, async (req, res) => {
    try {
        const { start_date, end_date } = req.query;

        let sql = `
            SELECT 
                operation_type,
                COUNT(*) as count
            FROM user_ctrl_log
            WHERE 1 = 1
        `;
        let params = [];

        if (start_date) {
            sql += ` AND DATE(operation_time) >= ?`;
            params.push(start_date);
        }
        if (end_date) {
            sql += ` AND DATE(operation_time) <= ?`;
            params.push(end_date);
        }

        sql += ` GROUP BY operation_type ORDER BY count DESC`;

        const [result] = await db.execute(sql, params);

        res.json({
            success: true,
            message: '获取操作类型统计成功',
            data: result
        });
    } catch (error) {
        console.error('获取操作类型统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取操作类型统计失败',
            error: error.message
        });
    }
});

// 获取操作状态统计
router.get('/status', authenticateToken, async (req, res) => {
    try {
        const { start_date, end_date } = req.query;

        let sql = `
            SELECT 
                status,
                COUNT(*) as count
            FROM user_ctrl_log
            WHERE 1 = 1
        `;
        let params = [];

        if (start_date) {
            sql += ` AND DATE(operation_time) >= ?`;
            params.push(start_date);
        }
        if (end_date) {
            sql += ` AND DATE(operation_time) <= ?`;
            params.push(end_date);
        }

        sql += ` GROUP BY status`;

        const [result] = await db.execute(sql, params);

        res.json({
            success: true,
            message: '获取操作状态统计成功',
            data: result
        });
    } catch (error) {
        console.error('获取操作状态统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取操作状态统计失败',
            error: error.message
        });
    }
});

// 获取用户操作排行
router.get('/user-ranking', authenticateToken, async (req, res) => {
    try {
        const { start_date, end_date, limit = 10 } = req.query;

        let sql = `
            SELECT 
                ucl.username,
                e.emp_name,
                COUNT(*) as operation_count
            FROM user_ctrl_log ucl
            LEFT JOIN user u ON ucl.username = u.username
            LEFT JOIN employee e ON u.emp_id = e.emp_id
            WHERE 1 = 1
        `;
        let params = [];

        if (start_date) {
            sql += ` AND DATE(ucl.operation_time) >= ?`;
            params.push(start_date);
        }
        if (end_date) {
            sql += ` AND DATE(ucl.operation_time) <= ?`;
            params.push(end_date);
        }

        const limitNum = parseInt(limit) || 10;
        sql += ` GROUP BY ucl.username, e.emp_name ORDER BY operation_count DESC LIMIT ?`;
        params.push(limitNum);

        const [result] = await db.execute(sql, params);

        res.json({
            success: true,
            message: '获取用户操作排行成功',
            data: result
        });
    } catch (error) {
        console.error('获取用户操作排行失败:', error);
        res.status(500).json({
            success: false,
            message: '获取用户操作排行失败',
            error: error.message
        });
    }
});

// 导出日志
router.get('/export', authenticateToken, async (req, res) => {
    try {
        const {
            username,
            operation_type,
            operation_module,
            status,
            start_date,
            end_date
        } = req.query;

        let sql = `
            SELECT 
                ucl.log_id,
                ucl.username,
                e.emp_name,
                ucl.operation_type,
                ucl.operation_module,
                ucl.operation_desc,
                ucl.ip_address,
                ucl.operation_time,
                ucl.status,
                ucl.error_message
            FROM user_ctrl_log ucl
            LEFT JOIN user u ON ucl.username = u.username
            LEFT JOIN employee e ON u.emp_id = e.emp_id
            WHERE 1 = 1
        `;
        let params = [];

        if (username) {
            sql += ` AND ucl.username LIKE ?`;
            params.push(`%${username}%`);
        }
        if (operation_type) {
            sql += ` AND ucl.operation_type = ?`;
            params.push(operation_type);
        }
        if (operation_module) {
            sql += ` AND ucl.operation_module LIKE ?`;
            params.push(`%${operation_module}%`);
        }
        if (status) {
            sql += ` AND ucl.status = ?`;
            params.push(status);
        }
        if (start_date) {
            sql += ` AND DATE(ucl.operation_time) >= ?`;
            params.push(start_date);
        }
        if (end_date) {
            sql += ` AND DATE(ucl.operation_time) <= ?`;
            params.push(end_date);
        }

        sql += ` ORDER BY ucl.operation_time DESC`;

        const [result] = await db.execute(sql, params);

        res.json({
            success: true,
            message: '导出用户控制日志成功',
            data: result
        });
    } catch (error) {
        console.error('导出用户控制日志失败:', error);
        res.status(500).json({
            success: false,
            message: '导出用户控制日志失败',
            error: error.message
        });
    }
});

module.exports = router; 